package cn.lg.soar.system.general.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.CurrentProxy;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.system.api.enums.SysConfigTypeEnum;
import cn.lg.soar.system.general.entity.SysConfig;
import cn.lg.soar.system.general.mapper.SysConfigMapper;
import cn.lg.soar.system.general.service.ISysConfigService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统配置
 * @author luguoxiang
 * @since 2023-07-13
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@CacheConfig(cacheNames = "CFG", cacheManager = "remote")
public class SysConfigServiceImpl extends BaseServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService, CurrentProxy<ISysConfigService> {

    @Cacheable(key = "#code")
    @Override
    public String get(String code) {
        SysConfig sysConfig = baseMapper.selectById(code);
        if (sysConfig == null) {
            return null;
        }
        return sysConfig.getValue();
    }

    @CacheEvict(key = "#code")
    @Override
    public boolean set(String code, String value) {
        // 必须先在数据库配置
        SysConfig config = new SysConfig();
        config.setCode(code);
        config.setValue(value);
        return saveOrUpdate(config);
    }

    @Override
    public Map<String, String> map(String[] codes) {
        Map<String, String> map = new HashMap<>(codes.length);
        ISysConfigService proxy = proxy();
        for (String code : codes) {
            map.put(code, proxy.get(code));
        }
        return map;
    }

    @Override
    public SysConfig getOtherById(String id) {
        return getOne(
                Wrappers.<SysConfig>lambdaQuery()
                        .eq(SysConfig::getCode, id)
                        .eq(SysConfig::getType, SysConfigTypeEnum.other)
        );
    }

    @Override
    @CacheEvict(key = "#id")
    public boolean removeOtherById(String id) {
        return remove(
                Wrappers.<SysConfig>lambdaQuery()
                        .eq(SysConfig::getCode, id)
                        .eq(SysConfig::getType, SysConfigTypeEnum.other)
        );
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeOtherByIds(Collection<String> ids) {
        ISysConfigService proxy = proxy();
        for (String id : ids) {
            AssertUtil.isTrue(proxy.removeOtherById(id), "操作失败");
        }
    }
}
